package com.ytkj.ygAssist.server;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ytkj.ygAssist.server.util.DateUtil;
import com.ytkj.ygAssist.server.util.HttpGetUtil;
import com.ytkj.ygAssist.tools.MyLog;

import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class GetHistoryBuyRecord {
    private String buyTime;//购买时间
    private Integer buyID;//购买ID
    private String price;//商品价格
    private ConcurrentHashMap<Integer, String> mTreeMap = new ConcurrentHashMap<Integer, String>();

    public static String getCodeRNO(String buyID, String buyTime, String price) {
        GetHistoryBuyRecord getHistoryBuyRecord = new GetHistoryBuyRecord();
        getHistoryBuyRecord.buyTime = buyTime;
        getHistoryBuyRecord.buyID = Integer.valueOf(buyID);
        getHistoryBuyRecord.price = price;
        return getHistoryBuyRecord.GetBuyGoodsCode();
    }

    /*
     * 获取幸运云购码
     */
    public String GetBuyGoodsCode() {
        MyLog.outLog("正在查中奖码：", buyTime, "buyID", buyID);
        final String[] buyTimeDate = DateUtil.getBuyTime(buyTime);
        int FIdx = 1;
        while (FIdx < 220) {
            MyLog.outLog("正在查询", buyTime, "第", FIdx);
            GetBuyRecordData(FIdx, buyTimeDate[0], buyTimeDate[1]);
            if (mTreeMap.size() > 0) {
                MyLog.outLog("查询到了购买记录，开始查询前100条");
                for (int i = 0; i < 5; i++) {
                    FIdx += 20;
                    final int idx = FIdx;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            GetBuyRecordData(idx, buyTimeDate[0], buyTimeDate[1]);
                        }
                    }).start();
                }
                break;
            }
            FIdx += 20;
        }

        int computeWinCodeNum = 0;
        String winCode = null;
        while (winCode == null && computeWinCodeNum < 30000) {
            winCode = computeWinCode();
            MyLog.threadSleep(10);
            computeWinCodeNum++;
        }
        return winCode;
    }

    /*计算中奖码*/
    private String computeWinCode() {
        String winCode = null;
        if (mTreeMap.size() == 100) {
            BigInteger sumTotal = BigInteger.valueOf(0);
            for (String map : mTreeMap.values()) {
                sumTotal = sumTotal.add(new BigInteger(map));
            }
            MyLog.outLog("查询计算总和", sumTotal.toString());
            winCode = sumTotal.remainder(new BigInteger(price)).add(BigInteger.valueOf(10000001)).toString();
            MyLog.outLog("计算中奖码", winCode);
        }
        return winCode;
    }

    private void GetBuyRecordData(int FIdx, String BTime, String ETime) {
        GetBuyRecordData(FIdx, BTime, ETime, 0);
    }

    /*获取历史购买记录并格式化*/
    private void GetBuyRecordData(int FIdx, String BTime, String ETime, int selectNum) {
        if (selectNum < 3) {
            try {
                String buyRecord = GetBuyRecord(FIdx, BTime, ETime);
                MyLog.outLog("获取历史记录", FIdx, buyRecord);
                formatData(buyRecord, buyTime);
            } catch (Exception e) {
                e.printStackTrace();
                MyLog.threadSleep(100);
                selectNum++;
                GetBuyRecordData(FIdx, BTime, ETime, selectNum);
            }
        }
    }

    /*获取历史购买记录数据*/
    private String GetBuyRecord(int FIdx, String BTime, String ETime) {
        StringBuffer getUrl = new StringBuffer();
        getUrl.append("http://api.1yyg.com/JPData?action=getHistoryBuyRecord&FIdx=").append(FIdx);
        getUrl.append("&EIdx=").append(FIdx + 19);
        getUrl.append("&BTime=").append(BTime);
        getUrl.append("&ETime=").append(ETime);
        getUrl.append("&isCount=1");
        return HttpGetUtil.getHttpData(getUrl.toString(), "http://www.1yyg.com/HistoryBuyRecords.html");
    }

    /*
     * 输出获取到的信息
     */
    private void formatData(String content, String buyTime) {
        String data = content.substring(content.indexOf("\"data\":") + 7, content.length() - 2);
        List<Map<String, String>> dataList = new Gson().fromJson(data, new TypeToken<List<Map<String, String>>>() {
        }.getType());
        for (Map<String, String> maps : dataList) {
            Integer mapBuyID = Integer.valueOf(maps.get("buyID"));
            if (mapBuyID <= buyID && mapBuyID > buyID - 100) {
                mTreeMap.put(mapBuyID, DateUtil.getDateFormatStringToInt(maps.get("buyTime")));
            }
        }
    }

}
